#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>

#include <iostream>
using namespace std;

typedef uint64_t uint64;
typedef uint32_t uint32;
typedef uint16_t uint16;
typedef uint8_t uint8;

int main()
{
	int sockfd;
	char recvbuf[1024];
	struct sockaddr_in server_addr;
	
	if((sockfd=socket(AF_INET,SOCK_STREAM,0)) == 0)
	{
		printf("创建socket失败:%s\n",strerror(errno));
		exit(1);
	}
	else
	{
		printf("连接服务器成功！\n");
	}
	
	server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(7570);
    server_addr.sin_addr.s_addr=inet_addr("192.168.0.193");
	
	if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
	{
		printf("连接服务器失败：%s\n",strerror(errno));
		exit(1);
	}
	else
	{
		printf("连接服务器成功！\n");
	}
	
	uint16* bufSend;
	bufSend = (uint16*)malloc(sizeof(uint16)*2);
	memset(bufSend,0,2*sizeof(uint16));
	
	uint16  head = 0x015;
	uint16  headto = 0x006;
	uint32 length = 8;
	//uint16 end = 33;
	
	bufSend[0] = head;
	bufSend[1] = headto;
	bufSend[2] = length;
	//bufSend[4] = end;
	cout<<"bufSend[0]"<<bufSend[0]<<endl;
	cout<<bufSend[2]<<endl;
	//cout<<bufSend[4]<<endl;
	
	if(write(sockfd,bufSend,6)==-1)
	{
		printf("向服务器传数据失败：%s\n",strerror(errno));
		exit(1);
	}
	else
	{
		printf("向服务器传数据成功！\n");
	}
	
		
	int nbytes;
	if((nbytes=read(sockfd,recvbuf,1024))==-1)
    {
        //fprintf(stderr,"Read Error:%s\n",strerror(errno));
		printf("接收数据失败！\n");
        exit(1);
    }
	else
	{
		printf("接收数据成功！\n");
	}
	
	cout<<"nbytes:"<<nbytes<<endl;
	
   // recvbuf[nbytes]='\0';
   
   uint16 recvHead;
   uint16 recvLength;
   uint16 recvContent;
   uint16 recvTest1;
   uint16 recvTest2;
   
   recvHead  = recvbuf[0];
   recvLength = recvbuf[2];
   recvContent = recvbuf[4];
   recvTest1 = recvbuf[6];
   recvTest2 = recvbuf[8];
   
   cout<<"recvHead:"<<recvHead<<endl;
   cout<<"recvLength:"<<recvLength<<endl;
   cout<<"recvContent:"<<recvContent<<endl;
   cout<<"recvTest1:"<<recvTest1<<endl;
   cout<<"recvTest2:"<<recvTest2<<endl;
   
    printf("I have received:%s\n",recvbuf);
	
    close(sockfd);
	free(bufSend);
	
	return 0;
}

